package com.dotmedia.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dotmedia.dboperations.AdDatabaseOperations;
import com.dotmedia.entities.Ad;
import com.dotmedia.utils.StringUtils;

/**
 * This servlet receives the adRefCode and systemId and returns whether this tuple is unique or not.
 * 
 * The parameters which the servlet expects is -
 * <ul>
 * <li><code>adRefCode</code></li>
 * <li><code>systemId</code></li>
 * </ul>
 * 
 * This servlet returns whether this tuple is unique or not. So the possible results of this servlet are -
 * <ul>
 * <li><code>unique</code></li>
 * <li><code>not.unique</code></li>
 * <ul>
 */
public class AdRefCodeAndSystemIdValidationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger("dotmedia.servlets");
	private static final String PARAMETER_AD_REF_CODE = "adRefCode";
	private static final String PARAMETER_SYSTEM_ID = "systemId";

	private static final String RESULT_UNIQUE = "unique";
	private static final String RESULT_NOT_UNIQUE = "not.unique";

	private static final String RESPONSE_TEXT_HTML = "text/html";
	private static final String BLANK_STRING = "";

	public AdRefCodeAndSystemIdValidationServlet() {
		super();
	}

	/**
	 * This is the main method for the servlet. For both <code>GET</code> and <code>POST</code> requests, this method is executed
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("IN servlet AdRefCodeAndSystemIdValidationServlet");
		response.setContentType(RESPONSE_TEXT_HTML);
		// get the parameters
		String adRefCodeString = (String) request.getParameter(PARAMETER_AD_REF_CODE);
		String systemIdString = (String) request.getParameter(PARAMETER_SYSTEM_ID);
		int systemId = -1;
		boolean isValidated = true;
		if (StringUtils.isStringNull(adRefCodeString)) {
			logger.error("The adRefCode received in the servlet is null. Nothing to do");
			isValidated = false;
		}
		if (StringUtils.isStringNull(systemIdString)) {
			logger.error("The systemId received in the servlet is null. Nothing to do");
			isValidated = false;
		} else {
			try {
				systemId = Integer.parseInt(systemIdString);
			} catch (NumberFormatException numberFormatException) {
				logger.error("The systemId received is not an integer. Nothing to do. Received systemId: " + systemId);
				isValidated = false;
			}
		}
		String result = RESULT_NOT_UNIQUE;
		if (isValidated) {
			// got the adRefCode and systemId
			AdDatabaseOperations adDatabaseOperations = new AdDatabaseOperations();
			boolean isUnique = true;
			List<Ad> allAds = adDatabaseOperations.getAllAdEntities();
			adRefCodeString = adRefCodeString.trim();
			for (Ad currentAd : allAds) {
				if (currentAd.getAdRefCode() == null) {
					currentAd.setAdRefCode(BLANK_STRING);
				}
				if (currentAd.getSystem() != null && currentAd.getSystem().getId() != null) {
					if (currentAd.getAdRefCode().equals(adRefCodeString) && currentAd.getSystem().getId().intValue() == systemId) {
						logger.error("This pair of adRefCode and systemId are not unique.");
						isUnique = false;
						break;
					}
				}
			}
			if (isUnique) {
				result = RESULT_UNIQUE;
			} else {
				result = RESULT_NOT_UNIQUE;
			}
		} else {
			result = RESULT_NOT_UNIQUE;
		}
		logger.info("Writing result back. Result = " + result);
		response.getOutputStream().println(result);
		response.getOutputStream().flush();
		logger.info("OUT servlet AdRefCodeAndSystemIdValidationServlet");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

}
